/**
 * 
 */
package com.jiang.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * @author Administrator
 * @数据库连接工具类
 */
public class DBConnectionUtils {

	private static final String DBDRIVER = "com.mysql.jdbc.Driver";
	private static final String URL = "jdbc:mysql://localhost:3306/hrdb?useSSL=false";
	private static final String USERNAME = "root";
	private static final String PASSWORD = "123456";
	
	private DBConnectionUtils(){
		
	}
	// 考虑到同一个事务要用同一个连接，而多个线程各自有自己的数据库连接
	private static ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();
	
	/**
	 * @获取连接
	 * @return
	 */
	public static Connection getConnection(){
		
		Connection conn = threadLocal.get();
		if(conn == null){
			try {
				Class.forName(DBDRIVER);
				conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
				// 放入池子
				threadLocal.set(conn);
			} catch (ClassNotFoundException | SQLException e) {
				e.printStackTrace();
			}
		}
			
		return conn;
	}
	
	
	// 关闭连接
	public static void close(){
		
		Connection conn = threadLocal.get();
		if(conn != null){
			try {
				conn.close();
				// 池子中关掉
				threadLocal.remove();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
	}
	
	
}
